package tpoo.common.services.utils;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

import tpoo.common.services.Service;
import tpoo.common.services.exceptions.ServiceException;
import tpoo.common.utils.exceptions.ResourceException;

public class ServiceAdmin {
	
	private static ApplicationContext ctx= null;
	
	
	public static Service getService(String serviceName) throws ServiceException{
		Service result=null;
		try {
			if (ctx == null) {
				initialize();
			}
			result = (Service) ServiceAdmin.ctx.getBean(serviceName);
		} catch (NoSuchBeanDefinitionException e) {
			throw new ServiceException(e);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private static void initialize(){
		String LOG4J="classpath*:src/main/resources/log4j.xml";
		try {
			//Cargo todos la appContext.xml que haya en el classpath
			ctx =new ClassPathXmlApplicationContext("classpath*:appContext.xml");
			/*
			Resource rsc = ctx.getResource(LOG4J);
			if (!rsc.exists())
				throw new ResourceException(LOG4J);
			else
				PropertyConfigurator.configure(rsc.getURL());
			*/
		} catch (Exception e){
			e.printStackTrace();
		}
		/*
		String fileName= System.getProperty("springContext",null);
		if (fileName == null)
			throw new RuntimeException("Falta el parámetro springContext que indica el nombre del archivo de Spring");
	
		File curDir = new File(".");
		System.out.println(curDir.getAbsolutePath());
				
		ctx = new FileSystemXmlApplicationContext(fileName);
		*/
	}
	
	
}
